import Taro from '@tarojs/taro';
import request from '@/utils/request';
import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import { IBuyTicket, ITicket } from '@/types/ticket';
import { Cell, Checkbox } from '@nutui/nutui-react-taro';
import { ArrowRight } from '@nutui/icons-react-taro';
import { payment } from '@/utils/wxpay';
import { formatDate2 } from '@/utils/time';
import {
  couponPrice,
  dealCouponsOrGifts,
  dealHolidayCoupons,
  oneCouponPrice,
  pickOutCoupon,
  pickOutTicket,
  priceToStringDeformation,
} from '@/utils/price';
import { getUser } from '@/utils/user';
import { EnumUseStatus, ICoupon } from '@/types/coupon';
import ButtonOnce from '@/components/button-once';
import './index.less';
import { IOrder } from '@/types/order';

interface IOrderTotal {
  prepayId: string;
  price: number;
}

const goPrivacyPolicy = () => {
  Taro.navigateTo({ url: '/pages/clause-service-notice/index' });
};


/**
 * 新增订单请求
 */
const requestForAddOrderById = async (
  orderId: string,
  userId: string,
  coupon?: ICoupon
): Promise<IOrderTotal> => {
  const orderTotal = await request.post<IOrderTotal>(
    '/order/get-prepay-id',
    {
      userId,
      orderId: orderId,
      couponId: coupon?.id,
    },
    {
      errorMsg: '支付失败',
    }
  );
  return orderTotal;
};

/**
 * 格式化日期为年月日格式
 */
const formatToYMD = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

/**
 * 获取今天的日期字符串
 */
const getTodayDateStr = () => {
  const today = new Date();
  return today.toISOString();
};

export default function Index() {
  const [price, setPrice] = useState<number>(0);
  const [orderId, setOrderId] = useState<string>('');
  const [order, setOrder] = useState<any>();
  const [isRead, setIsRead] = useState<boolean>(false);
  const [currentCoupon, setCurrentCoupon] = useState<ICoupon>();
  const user = getUser();

  const router = useRouter();
  useEffect(() => {
    console.log("router.params",router.params);
    // 获取路由参数，订单价格
    const price = router?.params?.price ? +router.params.price : 0;
    const orderId = router?.params?.orderId || "";
    const time = router?.params?.time || "";
    const timeEnd = router?.params?.timeEnd || "";
    setPrice(price);
    setOrderId(orderId);
    
    const getOrder = async () => {
      // 获取订单详情
      const order = await request.get<IOrder>(`/order/detail?id=${orderId}`);
      console.log("order",order);
      setOrder(order);
    };
    getOrder();
    // 处理优惠券选择页的回传事件
    const handleCouponEvent = (data: { coupon: ICoupon }) => {
      setCurrentCoupon(data.coupon);
    };
    Taro.eventCenter.on('couponChoose', handleCouponEvent);
    return () => {
      Taro.eventCenter.off('couponChoose', handleCouponEvent);
    };
  }, []);

  /**
   * 支付成功后的回调
   */
  const onPaySuccess = () => {
    // 成功提示
    Taro.showToast({
      title: '支付成功',
      icon: 'none',
    });
    // 跳转到主页
    setTimeout(() => {
      Taro.navigateBack({ delta: 3 });
    }, 500);
  };

  /**
   * 支付取消/失败后的回调
   */
  const onFailed = () => {
    Taro.showToast({
      title: '支付失败',
      icon: 'none',
    });
    // 跳转到主页
    setTimeout(() => {
      Taro.navigateBack({ delta: 3 });
    }, 500);
  };

  /**
   * 发起支付
   */
  const initPayment = async () => {
    if (!isRead) {
      Taro.showToast({
        title: '请先阅读并同意多多帮服务须知',
        icon: 'none',
      });
      return;
    }
    if (!user?.id) {
      Taro.navigateTo({ url: '/pages/login/index' });
      return;
    }
    
    // 计算实际支付金额
    const actualPrice = Math.max(0.01, (price||0) - oneCouponPrice(price, currentCoupon));
    
    const orderTotal = await requestForAddOrderById(
      orderId,
      user?.id,
      currentCoupon
    );
    
    // 确保支付金额不小于0.01元
    const finalOrderTotal = {
      ...orderTotal,
      price: Math.max(0.01, orderTotal.price)
    };
    
    await payment(finalOrderTotal.prepayId, onPaySuccess, onFailed);
  };

  // 处理日期显示逻辑
  const getDisplayDate = () => {
    // 如果是扔垃圾订单类型（或者订单还未加载但预期是扔垃圾类型）且没有有效时间
    if ((order?.orderType === "trash" || !order) && (!order?.time || order?.time === "")) {
      return formatToYMD(getTodayDateStr());
    }
    
    // 如果有时间参数且不为空字符串，则使用传入的时间
    if (order?.time && order.time !== "") {
      return formatToYMD(order.time as string);
    }
    
    // 兜底情况，如果没有时间参数，也返回今天日期
    return formatToYMD(getTodayDateStr());
  };

  return (
    <View className="order-review">
      <Cell.Group>
        <Cell
          title={
            <View className="tickets-title">
              <View>多多帮任务：{order?.orderType === "trash" ? "扔垃圾" : "取快递"}</View>
              <View className="price-number">
                {priceToStringDeformation(price)}
              </View>
            </View>
          }
        />
        <Cell>
          <View className="tickets-box">
            <View className="buy-date">
              {getDisplayDate()}
              {router.params.timeEnd ? ` - ${formatToYMD(router.params.timeEnd as string)}` : ""}
            </View>
            <View className="tickets-item">
              <View>{order?.orderType === "trash" ? "代扔垃圾服务" : "代取快递服务"}</View>
              <View className="price-number">
                <View>¥ {price} x 1</View>
              </View>
            </View>
          </View>
        </Cell>
        <Cell>
          <View className="coupon-box">
            <View className="coupon-none">
              <View className="coupon-title">优惠券</View>
              <View
                className="description"
                onClick={() =>
                  Taro.navigateTo({
                    url: `/pages/coupon-use/index?detail=${
                      router.params.detail
                    }&couponId=${currentCoupon?.id || ''}`,
                  })
                }>
                选择优惠券 <ArrowRight className="icon" size={14} />
              </View>
            </View>
            {currentCoupon && (
              <View className="tickets-item">
                <View>{currentCoupon?.name}</View>
                <View className="price">
                  <View>
                    {priceToStringDeformation(
                      -oneCouponPrice(price, currentCoupon)
                    )}
                  </View>
                </View>
              </View>
            )}
          </View>
        </Cell>
      </Cell.Group>
      <Checkbox
        checked={isRead}
        onChange={(val) => setIsRead(val)}
        label={
          <>
            <Text>已阅读并同意</Text>
            <Text className="clause-link" onClick={goPrivacyPolicy}>
              《多多帮服务须知》
            </Text>
          </>
        }
      />

      <View className="empty"></View>

      <View className="bottom-box">
        <View className="total-price">
          <View>
            实付：
            <Text className="total-price-number">
              {priceToStringDeformation(
                Math.max(0.01, (price||0) - oneCouponPrice(price, currentCoupon))
              )}
            </Text>
          </View>
          <ButtonOnce type="primary" onClick={initPayment}>
            立即支付
          </ButtonOnce>
        </View>
        <View className="empty"></View>
      </View>
    </View>
  );
}
